package com.jhws.core.shiro.filter;

import com.jhws.business.comm.bo.TblCommDimBo;
import com.jhws.business.comm.service.ITblCommDimService;
import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.common.base.bo.JsonRespData;
import com.jhws.core.shiro.tokens.CustomAuthToken;
import com.jhws.util.StringUtils;
import com.jhws.util.jsonUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * SDK服务端api拦截器
 * Created by Administrator on 2017/3/20.
 */
public class CustomApiFilter extends AuthenticatingFilter {
    @Resource
    protected ITblCommDimService ITblCommDimService;
    @Resource
    private RedisTemplate stringTemplate;

    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response, Object mappedValue) {
        return false;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // TODO Auto-generated method stub
        String customId = WebUtils.toHttp(request).getHeader("customId");
        customId = customId == null ? WebUtils.toHttp(request).getParameter("customId") : customId;
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        /*
         *假如是webApi控制器，则继续做Web登录
         */
        if (WebUtils.toHttp(request).getRequestURL().toString().contains("/custom/web/")) {
            try {
                String webApiToken = WebUtils.toHttp(request).getParameter("webApiToken");
                ValueOperations listOperations = stringTemplate.opsForValue();
                String commCode = (String) listOperations.get(webApiToken);
                if (StringUtils.isEmpty(commCode)) {
                    Map map = new HashedMap();
                    map.put("httpStatus", 401);
                    map.put("errorInfo", "webToken 鉴权失败！");
                    map.put("content", "哎哟喂！页面发生了错误！您无权限执行此操作！");
                    WebUtils.issueRedirect(request, response, "/open/webApiError.x", map);
                    return false;
                }
                if (getSubject(request, response).isAuthenticated()) {
                    Session session = getSubject(request, response).getSession();
                    TblUserDimBo user = (TblUserDimBo) session.getAttribute(TblUserDimBo.USER_INFO_REFERENCE);
                /* 如果检测到小区切换，则将老的登录注销 */
                    if (!commCode.equals(user.getCommCode()))
                        getSubject(request, response).logout();
                }

                /* 认证动作前面已经做了，这里只是创建新的session */
                if (!getSubject(request, response).isAuthenticated()) {
                    CustomAuthToken token = (CustomAuthToken) createToken(customId, commCode, request, response);
                    getSubject(request, response).login(token);
                    Session session = getSubject(request, response).getSession();
                    TblUserDimBo user = new TblUserDimBo();
                    user.setCommCode(commCode);
                    user.setRoleCode("3602849065226");
                    session.setAttribute(TblUserDimBo.USER_INFO_REFERENCE, user);
                    session.setAttribute("loginType", "custom");
                    WebUtils.toHttp(response).setHeader("P3P", "CP=CAO PSA OUR");
                }
            } catch (Exception e) {
                e.printStackTrace();
                Map map = new HashedMap();
                map.put("httpStatus", 401);
                map.put("content", "哎哟喂！页面发生了错误！您无权限执行此操作！");
                map.put("errorInfo", Arrays.toString(e.getStackTrace()));
                WebUtils.issueRedirect(request, response, "/open/webApiError.x", map);
                return false;
            }
        } else {
            if (customId == null) {
                response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -1, "无customId信息")));
                return false;
            }

            String ownerCode = WebUtils.toHttp(request).getParameter("ownerCode");
            String noticeCode = WebUtils.toHttp(request).getParameter("noticeCode");
            if (ownerCode != null || noticeCode != null) {
                return true;
            }

            String commName = WebUtils.toHttp(request).getParameter("commName");
            List<TblCommDimBo> commDimBos = ITblCommDimService.findTblCommDimByWhere("where 1=1 and comm_name = '" + commName + "' and custom_id ='" + customId + "'");
            if (commDimBos.size() < 1) {
                response.getWriter().write(jsonUtil.beanToJsonObject(new JsonRespData("UNAUTHORIZED", -1, "无权限操作‘" + commName + "'小区")));
                return false;
            }
        }
        return true;
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        return null;
    }

    @Override
    protected AuthenticationToken createToken(String username, String password, ServletRequest request, ServletResponse response) {
        return new CustomAuthToken(username, password);
    }
}
